<template>
  <div class="layout-container confidence-evaluate">
    <FlowStep :activeStep="3" />
    <BaseInfoForm :showTitle="true" :sampleId="route.query.sampleId"/>
    <TagIcon :title="`导引头抗干扰性能推算表`" :style="tagIconStyle" />
    <div class="layout-container-table">
      <CommonTable
        :data="state.tableData"
        v-model:page="page"
        :total="total"
        v-loading="loading"
        :showPagination="false"
        :showSelection="false"
        :showIndex="false"
        @span-method="objectSpanMethod"
        @onQuery="onQuery"
      >
        <el-table-column prop="evaluateMetric" label="抗干扰性能评估指标" />
        <el-table-column prop="performanceResult" label="推算结果" />
        <el-table-column prop="unit" label="单位" />
      </CommonTable>
    </div>

    <div class="step-buttons common-buttons">
      <el-button type="primary" @click="onBack">上一步</el-button>
      <!-- <el-button type="primary" @click="onSave">保存</el-button> -->
      <el-button type="primary" @click="onExport">导出</el-button>
      <el-button type="primary" @click="onConfidenceEvaluate"
        >进行置信度评估</el-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import CommonTable from '@/components/common-table/index.vue';
import TagIcon from '@/components/tag-icon/index.vue';
import { Page } from '@/components/common-table/type';
import BaseInfoForm from '../../BaseInfoForm/index.vue';
import {
  httpAntiInterComputingeResult
} from '@/api/antiJamPerformCalculateSystem';
import { downloadFile } from '@/utils/tools';
import LineChart from '../LineEchart/index.vue';
import FlowStep from '../../FlowStep/index.vue'
import * as XLSX from 'xlsx';

let $router = useRouter();
const route = useRoute();

const tagIconStyle = reactive({ padding: '16px' });
const state = reactive<any>({
  tableData: [],
});
const loading = ref<boolean>(false);
const page = reactive<Page>({
  current: 1,
  pageSize: 20,
});
const total = ref<number>(0);

onMounted(() => {
  onQuery({ pageNo: 1 });
});

// 查询数据
const onQuery = (val: any) => {
  const params = {
    sampleId: route.query.sampleId,
    hisSampleId: route.query.hisSampleId,
    deviationFuseResult: route.query.deviationFuseResult,
  };
  loading.value = true;
  httpAntiInterComputingeResult(params).then((res) => {
    const result = res.data;
    loading.value = false;
    if (result) {
      const metricNameMap: { [key: string]: string } = {
        "distFollowAcc": "距离跟踪精度推算结果",
        "discoverDist": "发现距离推算结果",
        "angleFollowAcc": "角度跟踪精度推算结果",
        "hitRate": "命中率推算结果",
        "antiPressRate": "抗压制干扰成功率推算结果",
        "antiCheatRate": "抗欺骗干扰成功率推算结果",
        "vecFollowAcc": "速度跟踪精度推算结果",
        "followDist": "跟踪距离推算结果",
      };

      const rows = Object.keys(result).map((key) => {
        const metricName = key;
        return {
          evaluateMetric: metricNameMap[metricName] || metricName,
          performanceResult: result ? result[metricName] : '-',
          unit: '-' // 可以根据需要添加单位
        };
      });

      state.tableData = rows;
    } else {
      state.tableData = [];
    }

    total.value = state.tableData.length;
  });
};

// 合并列
const objectSpanMethod = (obj: any) => {
  const { row, column, rowIndex, columnIndex } = obj;
};

// 返回
const onBack = () => {
  $router.push({
    path: '/antiJamPerformCalculateSystem/computeAtlas',
    query: {
      hisSampleId: route.query.hisSampleId,
      sampleId: route.query.sampleId,
      deviationFuseResult: route.query.deviationFuseResult
    },
  });
};

// 保存
// const onSave = () => {};

// 导出
const onExport = () => {
  ElMessageBox.confirm('你确定要导出excel文件吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      downloadFile();
    });
}

// 下载文件
const downloadFile = () => {
  try {
    // 获取表格数据
    const tableData = state.tableData;

    // 定义固定的表头
    const headers = [
      '抗干扰性能评估指标',
      '推算结果',
      '单位'
    ];

    // 转换数据
    const exportData = tableData.map((row: any) => {
      return {
        '抗干扰性能评估指标': row.evaluateMetric,
        '推算结果': row.performanceResult,
        '单位': row.unit,
      };
    });

    // 创建一个新的工作簿
    const workbook = XLSX.utils.book_new();

    // 将数据转换为工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData, { header: headers });

    // 将工作表添加到工作簿中
    XLSX.utils.book_append_sheet(workbook, worksheet, `${route.query.sampleName}的置信度评估结果`);
   
    // 生成 Excel 文件并下载
    XLSX.writeFile(workbook, `${route.query.sampleName}的置信度评估结果.xlsx`);
  } catch (error) { 
    ElMessage.error('导出失败，请重试');
  }
}

// 进行置信度评估
const onConfidenceEvaluate = () => {
  $router.push({
    path: '/antiJamPerformCalculateSystem/confidenceEvaluate',
    query: {},
  });
};
</script>

<style lang="scss" scoped>
@import '@/assets/style/buttons';
.confidence-evaluate {
    .layout-container-table {
      .el-button--small {
        background: transparent;
        color: rgba(24, 81, 237, 1);
      }
    }
  
    .step-buttons {
      display: flex;
      justify-content: center;
      box-shadow: 0px 0px 10px rgba(218, 222, 224, 1);
      padding: 10px 0;
    }
  }
  .el-button {
      background: rgb(1, 18, 90);
      border: 0;
    }

</style>
